/**
 *  JSimProd - Java simulation code for production processes
 *  Copyleft Jorge Mira Yagüe <jorge.mira.yague@gmail.com>
 *  Universidad de Alicante 2009
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/*
 * frmItem.java
 *
 * Created on 16-feb-2009, 12:14:56
 */
package gui.forms;

import gui.tools.Receiver;
import gui.tools.models.TMTask;
import java.awt.Color;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import javax.swing.event.TableModelEvent;
import lib.model.FactoryModel;
import lib.model.ICColor;
import lib.model.ItemCategory;
import lib.model.Task;

/**
 *
 * @author jorge
 */
public class FrmItemCategory extends javax.swing.JDialog implements Receiver {

    private FactoryModel factoryModel;
    private Receiver parent;
    private ItemCategory itemCategory;
    private int index;
    private boolean add;

    /** Creates new form frmItem */
    public FrmItemCategory(ItemCategory itemCategory,
            FactoryModel factoryModel,
            Receiver parent) {
        initComponents();

        this.getRootPane().setDefaultButton(btnSave);

        tbTasks.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    btnTaskEditActionPerformed(null);
                }
            }
        });

        String fileString = "/res/icons/logo.png";
        try {
            Image icon = ImageIO.read(getClass().getResource(fileString));
        } catch (java.io.IOException ioe) {
            System.out.println("Error loading file: " + fileString);
        }

        this.factoryModel = factoryModel;
        this.itemCategory = itemCategory;
        this.parent = parent;

        for (ICColor icc : ICColor.values()) {
            cbColor.addItem(icc);
        }

        if (itemCategory != null) {
            this.setTitle("Edit item category: " + itemCategory.getName());
            txtName.setText(itemCategory.getName());
            txtDescription.setText(itemCategory.getDescription());
            tbTasks.setModel(new TMTask(itemCategory.getTasks()));
            cbColor.setSelectedItem(itemCategory.getColor());
        } else {
            this.setTitle("New item category:");
            tbTasks.setModel(new TMTask(new ArrayList<Task>()));
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblName = new javax.swing.JLabel();
        lblColor = new javax.swing.JLabel();
        lblDescription = new javax.swing.JLabel();
        lblColorExample = new javax.swing.JLabel();
        txtDescription = new javax.swing.JTextField();
        txtName = new javax.swing.JTextField();
        btnCancel = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        lblTasks = new javax.swing.JLabel();
        spTasks = new javax.swing.JScrollPane();
        tbTasks = new javax.swing.JTable();
        btnTaskAdd = new javax.swing.JButton();
        btnTaskDelete = new javax.swing.JButton();
        btnTaskEdit = new javax.swing.JButton();
        cbColor = new javax.swing.JComboBox();

        setModal(true);
        setResizable(false);

        lblName.setText("Name:");

        lblColor.setText("Color:");

        lblDescription.setText("Description:");

        lblColorExample.setBackground(new java.awt.Color(255, 255, 255));
        lblColorExample.setText("     ");
        lblColorExample.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        lblColorExample.setOpaque(true);

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        lblTasks.setText("Tasks:");

        tbTasks.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        spTasks.setViewportView(tbTasks);

        btnTaskAdd.setText("Add...");
        btnTaskAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTaskAddActionPerformed(evt);
            }
        });

        btnTaskDelete.setText("Delete");
        btnTaskDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTaskDeleteActionPerformed(evt);
            }
        });

        btnTaskEdit.setText("Edit...");
        btnTaskEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTaskEditActionPerformed(evt);
            }
        });

        cbColor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbColorActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(spTasks, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 472, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblDescription)
                            .addComponent(lblName))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblColorExample, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cbColor, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtDescription, javax.swing.GroupLayout.DEFAULT_SIZE, 385, Short.MAX_VALUE)))
                    .addComponent(lblColor, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblTasks, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnTaskAdd)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnTaskEdit)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnTaskDelete))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnSave)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnCancel)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblName)
                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblDescription)
                    .addComponent(txtDescription, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblColor)
                    .addComponent(lblColorExample, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbColor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblTasks)
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnTaskDelete)
                    .addComponent(btnTaskEdit)
                    .addComponent(btnTaskAdd))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(spTasks, javax.swing.GroupLayout.DEFAULT_SIZE, 305, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancel)
                    .addComponent(btnSave))
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-500)/2, (screenSize.height-521)/2, 500, 521);
    }// </editor-fold>//GEN-END:initComponents

    private void btnTaskAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTaskAddActionPerformed
        add = true;
        if (setItemCategory()) {
            new FrmTask(null, factoryModel, itemCategory, this).setVisible(true);
        }
    }//GEN-LAST:event_btnTaskAddActionPerformed

    private void btnTaskDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTaskDeleteActionPerformed
        int delete = JOptionPane.showConfirmDialog(this,
                "Are you sure to delete the selected task?",
                "Confirm your decision",
                JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.QUESTION_MESSAGE);
        if (delete == JOptionPane.CANCEL_OPTION) {
            return;
        }
        int row = tbTasks.getSelectedRow();
        if (row >= 0) {
            TMTask tmt = (TMTask) tbTasks.getModel();
            tmt.removeTask(row);
            tbTasks.setModel(tmt);
            tbTasks.tableChanged(new TableModelEvent(tbTasks.getModel()));
        }
    }//GEN-LAST:event_btnTaskDeleteActionPerformed

    private void btnTaskEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTaskEditActionPerformed
        index = tbTasks.getSelectedRow();
        add = false;
        if (index >= 0) {
            TMTask tmt = (TMTask) tbTasks.getModel();
            Task task = tmt.getTask(index);
            if (setItemCategory()) {
                new FrmTask(task, factoryModel, itemCategory, this).setVisible(true);
            }
        }
    }//GEN-LAST:event_btnTaskEditActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        if (setItemCategory()) {
            this.setVisible(false);
            parent.reciveObject(itemCategory);
        }
    }//GEN-LAST:event_btnSaveActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_btnCancelActionPerformed

    private void cbColorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbColorActionPerformed
        Color color;
        switch ((ICColor) cbColor.getSelectedItem()) {
            case BLUE:
                color = Color.BLUE;
                break;
            case GRAY:
                color = Color.GRAY;
                break;
            case GREEN:
                color = Color.GREEN;
                break;
            case ORANGE:
                color = Color.ORANGE;
                break;
            case PINK:
                color = Color.PINK;
                break;
            case RED:
                color = Color.RED;
                break;
            case WHITE:
                color = Color.WHITE;
                break;
            case YELLOW:
                color = Color.YELLOW;
                break;
            default:
                color = Color.BLACK;
        }
        lblColorExample.setBackground(color);
    }//GEN-LAST:event_cbColorActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnTaskAdd;
    private javax.swing.JButton btnTaskDelete;
    private javax.swing.JButton btnTaskEdit;
    private javax.swing.JComboBox cbColor;
    private javax.swing.JLabel lblColor;
    private javax.swing.JLabel lblColorExample;
    private javax.swing.JLabel lblDescription;
    private javax.swing.JLabel lblName;
    private javax.swing.JLabel lblTasks;
    private javax.swing.JScrollPane spTasks;
    private javax.swing.JTable tbTasks;
    private javax.swing.JTextField txtDescription;
    private javax.swing.JTextField txtName;
    // End of variables declaration//GEN-END:variables

    public void reciveObject(Object object) {
        Task task = (Task) object;
        TMTask tmt = (TMTask) tbTasks.getModel();
        if (add) {
            tmt.addTask(task);
        } else {
            tmt.setTask(index, task);
        }
        tbTasks.setModel(tmt);
        tbTasks.tableChanged(new TableModelEvent(tbTasks.getModel()));
    }

    private boolean setItemCategory() {
        if (txtName.getText().equals("")) {
            itemCategory = new ItemCategory(txtName.getText(),
                    txtDescription.getText(),
                    (ICColor) cbColor.getSelectedItem());
            itemCategory.setTasks(((TMTask) tbTasks.getModel()).getTasks());
            return true;
        } else {
            JOptionPane.showMessageDialog(rootPane,
                    "Error:\n Name cannot be empty.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
            return false;
        }
    }
}
